package com.piece.admin.context.init;

import com.piece.core.db.util.DataBaseUtil;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.util.object.BeanUtil;
import com.piece.core.web.initializer.SystemScript;
import com.piece.module.generator.model.TbSysDb;
import com.piece.module.generator.service.TbSysDbService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 加载数据源配置
 */
@Slf4j
@Component
public class InitDataSource implements SystemScript {

    @Resource
    private TbSysDbService tbSysDbService;

    @Override
    public String getScriptName() {
        return "加载数据源配置";
    }

    @Override
    public void doInit() throws Exception {
        HashMap<String, Object> condition = new HashMap<>();
        condition.put("status", StatusType.NORMAL.getCode());
        List<TbSysDb> dbs = tbSysDbService.findByCondition(condition);

        dbs.forEach(db -> {
            Map<String, Object> target = new HashedMap();
            BeanUtil.beanToMap(db, target);
            DataBaseUtil.createDataSource(target);
        });
    }

    @Override
    public Integer getIndex() {
        return Integer.MAX_VALUE;
    }
}
